import React from "react";
import {Button,  Divider,  Modal} from 'antd/lib';
import ProgressTable from "@/components/contract/ProgressTable";
import ContractProgress from "@/services/contractprogress";
import notification from "@/services/notification";
import {get} from "lodash";
import CheckDialog from "@/components/workflow/CheckDialog";
import {currentUser} from "@/services/auth";
import Workflow from "@/services/workflow";
import moment from "moment";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import GlobalFunctions from '@/store/globalFunctions';
import {createBrowserHistory} from 'history';
const customHistory = createBrowserHistory();
const { confirm } = Modal;
export default class ProgressToolbar extends React.Component {
  state = {
    loading: true,
    isnew: true,
    id: 0,
    isedit:true,
    isdel:false,
    allow_col:[],
    colcontrol:false,
    userid: currentUser.id,//--操作员ID
    status: 0,//--状态
    annex:[],//--附件
  };
  componentWillMount() {

     if(this.props.id<1 || this.props.id===undefined ){
       ContractProgress.getid({id: 0}).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
        });
      });
     }else{
        this.setState({
          id: this.props.id,
          isnew: false,
          loading: false,
        });
       this.iseditData(this.props.id);
       this.refreshData(this.props.id) ;
     }
  }
  refreshData(id) {
    ContractProgress.get({id: id}).then(data => {
      if (data.id > 0) {
        this.setState({
          id: data.id,//
          userid: data.userid,//--操作员ID
          bill_date: moment(data.bill_date),//--申请日期
          contractsid: data.contractsid,//--合同
          code: data.code,//----编号
          name: data.name,//--名称
          status: data.status,//--状态
          percent: data.percent,//
          message: data.message,//--纪录事项
          loading: false,
        });
      } else {
        this.setState({
          loading: false,
          id: id,
          userid: currentUser.id,//--操作员ID
          bill_date: moment(),//--申请日期
          contractsid: "",//
          code: "",//----编号
          name: "",//--名称
          status: 0,//--状态
          percent: 0,
          message: "",//--纪录事项
        });
      }
    }).catch(error => {
        this.setState({
          loading: false,
          id: id,
          userid: currentUser.id,//--操作员ID
          bill_date: moment(),//--申请日期
          contractsid: "",//--经办部门
          code: "",//----合同编号
          name: "",//--合同名称
          status: 0,//--状态
          percent: 0,
          message: "",//--纪录事项
        });
      });
}
  handleadd = () => {
       ContractProgress.getid({id: 0}).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
          isedit:true,
          isdel:false,
        });
        this.refreshData(data[0].id)
      });
  };
  ///|| str.match(/^[\s]*$/)
  isEmptyobj = (str) => {
	if(str==='' || str === null || str === 'null' || str === undefined || str === 'undefined'){
		return true;
	}else{
		return false;
	}
}
  handleSave = () => {
    if(this.child.state.status ===0 && currentUser.id !==this.child.state.userid){
      notification.error("草稿状态，不是制单人，不能保存！");
      return;
    }
    if(this.child.state.status ===2){
      notification.error("已审批，不能保存！");
      return;
    }
    let  contractsid=this.child.state.contractsid;
    if(GlobalFunctions.isEmptyobj(contractsid)){
      notification.error("合同不能为空！");
      return;
    }
    let  code=this.child.state.code;
    if(GlobalFunctions.isEmptyobj(code)){
      notification.error("编号不能为空");
      return;
    }
    let  name=this.child.state.name;
    if(GlobalFunctions.isEmptyobj(name)){
      notification.error("名称不能为空");
      return;
    }
     let  percent=0;
    // if(GlobalFunctions.isEmptyobj(name)){
    //   notification.error("进度不能为空");
    //   return;
    // }
    let  annex=[]
    this.child.state.annex.forEach(file => {
      if(file.status==="done") {
         const b=[{
                  uid: file.uid,
                  name: file.name,
                  status: file.status,
                  bytstatus:file.bytstatus,
                  url: file.url
          }];
        if (annex.length < 1) {
          annex = b;
        } else {
          annex.push.apply(annex, b);
        }
      }
        });
    let data={id: this.child.state.id,//
            userid: this.child.state.userid,//--操作员ID
            bill_date: this.child.state.bill_date,//--申请日期
            contractsid: contractsid,
            code: code,//----合同编号
            name: name,//--合同名称
            percent: percent,
            status: this.child.state.status,//--状态
            message: this.child.state.message,
           sourcetype: this.child.state.sourcetype,
           sourceid: this.child.state.sourceid,
           annex: annex,
    }
    if(this.state.isnew) {
      ContractProgress.create(data)
        .then(() => {
           this.setState({
                isnew: false,
                loading: false,
                isedit: true,
                id: data.id,//
                userid: data.userid,//--操作员ID
                bill_date: data.bill_date,//--申请日期
                contractsid: data.contractsid,
                code: data.code,//----合同编号
                name: data.name,//--合同名称
                percent: data.percent,
                status: data.status,//--状态
                message: data.message,
               sourcetype: data.sourcetype,
               sourceid: data.sourceid,
               annex: annex,
              });
          notification.success("合同违约登记单新增成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }else{
      ContractProgress.save(data)
        .then(() => {
          notification.success("合同违约登记单修改成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }
  };
  handleDelete = () => {
    if(this.child.state.status !==0){
      notification.error("不是草稿状态，不能删除！");
      return;
    }
    confirm({
      title: '确定删除合同违约登记单?',
      icon: <WarningOutlined />,
      content: this.child.state.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractProgress.delete({id: this.state.id}).then(()=>{
          notification.success("合同违约登记单删除成功.");
             ContractProgress.getid({id: 0}).then(data => {
              this.setState({
                id: data,
                isnew: true,
                loading: false,
                isedit: true,
              });
              this.refreshData(data)
            });
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  iseditData(id) {
      let item = {
        bill: "contractprogress",
        billtype:0,
        billid: id,
        userid: currentUser.id
      }
      Workflow.edit(item).then(data => {
        if(data.length>0){
              this.setState({
                isedit: data[0].edit,
                isdel: data[0].del,
                allow_col:data[0].allow_col,
                colcontrol:data[0].colcontrol,
              });
        }
      }).catch(error => {
              this.setState({
                isedit: true,
                isdel: true,
                allow_col:[],
                colcontrol:false,
              });
        });
  };
  handlebackpage= () => {
    customHistory.goBack();
  };
  handleCheck = () => {
    if(!currentUser.isAudit){
      notification.error("没有权限.");
      return;
    }
    let item={
      bill:"contractprogress",
      id:this.state.id,
      message:"",
      status: this.child.state.status,
      altermsg: "",
      warnsealuser:"",
    }
    if(this.state.status===0){
      item = {
        bill: "contractprogress",
        billtype: 0,
        billid: this.state.id,
        next_type: 1,
        message:'<div>同意</div>',
        userid: currentUser.id,
        billdate: this.state.bill_date.format('YYYY-MM-DD'),
        orgunitid: this.state.departmentid,
        status: this.state.status,
        warnsealuser:"",
        billuserid: currentUser.id,
      }
      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
          this.iseditData(this.state.id);
          this.refreshData(this.state.id);
          notification.success(data[0].message);
        } else {
          notification.error(data[0].message);
        }
      })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }else{
      CheckDialog.showModal({bill_check: item})
      .onClose((result = {}) => {
          if (result.success) {
            this.iseditData(this.state.id);
            this.refreshData(this.state.id);
            // this.setState({
            //   id: item.id,
            // });
          }
        }).onDismiss(() => {
    //     navigateTo("contract/progress", true);
        });
      }
  };
  render() {
    if (this.state.loading) return null;
    const data={
      id: this.state.id,//
      userid: this.state.userid,//--操作员ID
      bill_date: this.state.bill_date,//--申请日期
      contractsid: this.state.contractsid,//--合同
      code: this.state.code,//----编号
      name: this.state.name,//--名称
      status: this.state.status,//--状态
      percent: this.state.percent,//
      message: this.state.message,//--纪录事项
    };
    return(
      <div>
        <div style={{ marginBottom: 16 }}>
        <Button type="primary" style={{margin:"10px"}} onClick={() => this.handlebackpage()}>
            <i className="fa fa-reply m-r-5" />
            返回
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleadd()}>
            <i className="fa fa-plus m-r-5" />
            新增
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleSave()} disabled ={!this.state.isedit}>
            <i className="fa fa-save m-r-5" />
            保存
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleDelete()} disabled ={this.state.isdel}>
            <i className="fa fa-trash m-r-5" />
            删除
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleCheck()}>
            <i className="fa fa-check m-r-5" />
            {this.state.status===0 ? "提交":"审核"}
          </Button>
        </div>
        <div>
          <ProgressTable data={data}   isedit={this.state.isedit}  isnew={this.state.isnew} 
          allow_col={this.state.allow_col} colcontrol={this.state.colcontrol}
          onRef={(ref) => { this.child = ref; }}/>
        </div>
      </div>
    );
  };
}

